package com.study.springsecurity.controller;

import com.study.springsecurity.pojo.Result;
import com.study.springsecurity.pojo.dto.UserInfoDto;
import com.study.springsecurity.pojo.entity.UserEntity;
import com.study.springsecurity.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户相关信息
 */
@Slf4j
@RestController
@RequestMapping("/userInfo")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 查询用户列表
     *
     * @return
     */
    @GetMapping("/queryUserInfoList")
    public Result<List<UserEntity>> queryUserInfoList() {
        return new Result<>(userInfoService.list());
    }

    /**
     * 根据ID查询用户信息
     *
     * @param userId
     * @return
     */
    @GetMapping("/queryUserInfoById")
    public Result<UserEntity> queryUserInfoById(@RequestParam("userId") Long userId) {
        return new Result<>(userInfoService.getById(userId));
    }

    /**
     * 保存或更新用户信息
     *
     * @param userInfoDto
     * @return
     */
    @PostMapping("/saveUserInfo")
    public Result<Long> saveUserInfo(@RequestBody UserInfoDto userInfoDto) {
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userInfoDto, userEntity);
        userEntity.setPassword(passwordEncoder.encode(userEntity.getPassword()));
        userInfoService.save(userEntity);
        return new Result<>(userEntity.getId());
    }
}
